import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {
  useMediaQuery,
  Grid,
  Typography,
  TextField,
  Button,
  Divider,
  Avatar,
} from '@material-ui/core';
import { useDispatch, useSelector } from 'react-redux';
import { SectionHeader } from 'components/molecules';
import { setArtistItem } from 'redux/actions/SearchArtistsAction';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { setLoading } from 'redux/actions/LoadingActions';
import { setCallbackError } from 'redux/actions/LoadingActions';
import { setPodcastItem } from 'redux/actions/PodcastsAction';
import { callGetApi, callPostApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  inputTitle: {
    fontWeight: 700,
    marginBottom: theme.spacing(1),
  },
  teamAvatar: {
    width: 150,
    height: 150,
    border: `${theme.spacing(1)}px solid ${theme.palette.background.paper}`,
    boxShadow: `0 2px 10px 0 ${theme.palette.cardShadow}`,
    marginTop: theme.spacing(1 / 2),
  },
  listGrid: {
    overflow: 'hidden',
    marginBottom: theme.spacing(3),
    '&:last-child': {
      marginBottom: theme.spacing(0),
    },
  },
  description: {
    marginLeft: '15px'
  }
}));

const Subscriptions = props => {
  const { className, ...rest } = props;
  const classes = useStyles();
  const dispatch = useDispatch();
  const history = useHistory();
  const profileData = useSelector((state) => state.auth.profileData)
  const [mSubscriptions, setSubscriptions] = useState([])

  const theme = useTheme();
  const isMd = useMediaQuery(theme.breakpoints.up('md'), {
    defaultMatches: true,
  });

  useEffect(() => {
    loadData();
  }, [])

  const loadData = async () => {
    callGetApi(`subscription/user_subscriptions?user_id=${profileData.id}`, dispatch, function callback(data) {
      setSubscriptions(data)
    })
  }

  const actionItem = (item) => {
    if (item.artist) {
      dispatch(setArtistItem(item.artist));
      history.push(`/artist/${item.artist.id}`);
    }
    else if (item.podcast) {
      dispatch(setPodcastItem(item.podcast));
      history.push(`/podcast/${item.podcast.id}`);
    }
  }

  const cancelSubscription = (item) => {
    const params = {
      user_id: profileData.id,
      subscription_item_id: item.subscription_item_id
    };
    callPostApi('subscription/cancel_subscription', params, dispatch, function callback(data) {
      dispatch(setCallbackError({
        title: 'Success',
        content: 'Successfully cancelled'
      }));
      loadData();
    })
  }

  return (
    <div className={className} {...rest}>
      <Grid container spacing={isMd ? 4 : 2}>
        <Grid item xs={12}>
          <Typography variant="h6" color="textPrimary">
            Subscriptions
          </Typography>
        </Grid>
        <Grid item xs={12}>
          <Divider />
        </Grid>
        <Grid container>
          {
            mSubscriptions.length > 0 ? (
              mSubscriptions.map((item, index) => (
                <Grid
                  key={index}
                  md={12}
                  item
                  container
                  spacing={isMd ? 4 : 2}
                  className={classes.listGrid}
                  direction={'row'}
                  style={{ 'margin': 0 }}
                  onClick={e => {
                    e.stopPropagation();
                    actionItem(item);
                  }}
                >
                  <Grid item md={3}>
                    <Avatar
                      {...{ src: item.artist ? item.artist.avatarURL : item.podcast.avatarURL }}
                      alt={ item.artist? 'Artist - ' + item.artist.name : 'Podcast - ' + item.podcast.name }
                      className={classes.teamAvatar}
                    />
                  </Grid>
                  <Grid item md={9}>
                    <SectionHeader
                      label=""
                      titleVariant="h5"
                      title={item.subscription_item.title}
                      subtitle={item.subscription_item.sub_title}
                      style={{ 'marginTop': '1em' }}
                      ctaGroup={[
                        <Typography variant="subtitle1" color="textSecondary">
                          {item.subscription_item.price + item.subscription_item.currency}
                        </Typography>,
                        <Button
                          variant="outlined"
                          color="secondary"
                          size={isMd ? 'large' : 'medium'}
                          className={classes.description}
                          onClick={e => {
                            e.stopPropagation();
                            if (window.confirm("Are you sure cancel the subscription?") == true) {
                              cancelSubscription(item);
                            }
                          }}
                        >
                          Cancel Subscribe
                        </Button>
                      ]}
                      align={'left'}
                      disableGutter
                    />
                  </Grid>
                </Grid>
              ))) : (
              <Typography variant="subtitle1" color="textSecondary" className={classes.description}>
                No Subscriptions
              </Typography>
            )
          }
        </Grid>
      </Grid>
    </div>
  );
};

Subscriptions.propTypes = {
  /**
   * External classes
   */
  className: PropTypes.string,
};

export default Subscriptions;
